package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.dto.dashboard.*;
import com.example.domain.entity.*;
import com.example.mapper.*;
import com.example.service.IDashBoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.example.domain.dto.dashboard.*;
import com.example.service.IDashBoardService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DashBoardService implements IDashBoardService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private ProductionPlanMapper productionPlanMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<DepartmentEquipmentStatus> equimentStatus() {
        // 获取所有部门的设备状态
        List<DepartmentEquipmentStatus> result = new ArrayList<>();
        
        // 查询所有设备
        QueryWrapper<Device> deviceQuery = new QueryWrapper<>();
        List<Device> devices = deviceMapper.selectList(deviceQuery);
        
        // 按部门分组统计
        Map<Integer, List<Device>> devicesByDept = devices.stream()
            .collect(Collectors.groupingBy(Device::getDeptId));
            
        devicesByDept.forEach((deptId, deptDevices) -> {
            DepartmentEquipmentStatus status = new DepartmentEquipmentStatus();
            status.setDeptId(deptId);
            status.setDeptName(deptMapper.getDeptName(deptId));
            status.setTotalEquipments(deptDevices.size());
            
            // 统计报废设备数量
            long scrapCount = deptDevices.stream()
                .filter(device -> "报废".equals(device.getStatus()))
                .count();
            status.setScrapEquipments((int) scrapCount);
            
            // 计算报废率
            status.setScrapRate(deptDevices.size() > 0 ? 
                (double) scrapCount / deptDevices.size() : 0.0);
                
            result.add(status);
        });
        
        return result;
    }

    @Override
    public Map<String, List<DepartmentMaterialStatus>> materialStatuses() {
        // 获取所有部门的物料状况
        
        // 查询所有物料
        QueryWrapper<Material> materialQuery = new QueryWrapper<>();
        List<Material> materials = materialMapper.selectList(materialQuery);
        
        // 按部门和物料类型分组统计
        Map<Integer, Map<String, List<Material>>> materialsByDeptAndType = materials.stream()
            .collect(Collectors.groupingBy(Material::getDeptId,
                    Collectors.groupingBy(Material::getMaterialType)));
                    
        Map<String, List<DepartmentMaterialStatus>> result = new HashMap<>();

        materialsByDeptAndType.forEach((deptId, typeMap) -> {
            int totalMaterials = typeMap.values().stream()
                .mapToInt(List::size)
                .sum();
                
            String deptName = deptMapper.getDeptName(deptId);
            List<DepartmentMaterialStatus> deptMaterialStatuses = new ArrayList<>();

            typeMap.forEach((type, typeMaterials) -> {
                DepartmentMaterialStatus status = new DepartmentMaterialStatus();
                status.setDeptId(deptId);
                status.setDeptName(deptName);
                status.setMaterialType(type);
                status.setMaterialCount(typeMaterials.size());
                status.setTotalMaterials(totalMaterials);
                status.setMaterialRatio(totalMaterials > 0 ? 
                    (double) typeMaterials.size() / totalMaterials : 0.0);
                    
                deptMaterialStatuses.add(status);
            });
            result.put(deptName, deptMaterialStatuses);
        });
        
        return result;
    }

    @Override
    public List<DepartmentPersonnelStatus> personnelStatuses() {
        // 获取所有部门的人员状况
        List<DepartmentPersonnelStatus> result = new ArrayList<>();
        
        // 查询所有人员
        QueryWrapper<Person> personQuery = new QueryWrapper<>();
        List<Person> persons = personMapper.selectList(personQuery);
        
        // 计算总人数
        int totalPersons = persons.size();
        
        // 按部门分组统计
        HashMap<Integer, List<Person>> personsByDept = new HashMap<>();
        for(Person person : persons) {
            Integer deptId = person.getDeptId();
            if(!personsByDept.containsKey(deptId)) {
                personsByDept.put(deptId, new ArrayList<>());
            }
            List<Person> personList = personsByDept.get(deptId);
            personList.add(person);
        }
            
        personsByDept.forEach((deptId, deptPersons) -> {
            DepartmentPersonnelStatus status = new DepartmentPersonnelStatus();
            status.setDeptId(deptId);
            status.setDeptName(deptMapper.getDeptName(deptId));
            status.setPersonnelCount(deptPersons.size());
            status.setPersonnelRatio(totalPersons > 0 ? 
                (double) deptPersons.size() / totalPersons : 0.0);
                
            result.add(status);
        });
        
        return result;
    }

    @Override
    public List<DepartmentProductionStatus> productionStatus() {
        // 获取所有部门的生产情况
        List<DepartmentProductionStatus> result = new ArrayList<>();
        
        // 查询所有生产计划
        QueryWrapper<ProductionPlan> planQuery = new QueryWrapper<>();
        List<ProductionPlan> plans = productionPlanMapper.selectList(planQuery);
        
        // 按部门分组统计
        Map<Integer, List<ProductionPlan>> plansByDept = plans.stream()
            .collect(Collectors.groupingBy(ProductionPlan::getDeptId));
            
        plansByDept.forEach((deptId, deptPlans) -> {
            DepartmentProductionStatus status = new DepartmentProductionStatus();
            status.setDeptId(deptId);
            status.setDeptName(deptMapper.getDeptName(deptId));
            status.setTotalPlans(deptPlans.size());
            
            // 统计已完成的计划数量
            long completedCount = deptPlans.stream()
                .filter(plan -> plan.getAuditStatus() == 1)
                .count();
            status.setCompletedPlans((int) completedCount);
            
            // 计算完成率
            status.setCompletionRate(deptPlans.size() > 0 ? 
                (double) completedCount / deptPlans.size() : 0.0);
                
            result.add(status);
        });
        
        return result;
    }

    @Override
    public List<DepartmentProductionDetail> productionDetail(Integer deptId) {
        // 获取指定部门的生产计划详情
        List<DepartmentProductionDetail> result = new ArrayList<>();
        
        // 查询该部门的所有生产计划
        QueryWrapper<ProductionPlan> planQuery = new QueryWrapper<>();
        planQuery.eq("dept_id", deptId);
        List<ProductionPlan> plans = productionPlanMapper.selectList(planQuery);
        
        String deptName = deptMapper.getDeptName(deptId);
        
        // 转换为详情对象
        plans.forEach(plan -> {
            DepartmentProductionDetail detail = new DepartmentProductionDetail();
            detail.setDeptId(deptId);
            detail.setDeptName(deptName);
            detail.setProductionPlanId(plan.getPlanId());
            detail.setProductName(plan.getProductName());
            detail.setPlannedQuantity(plan.getPlannedQuantity());
            detail.setActualQuantity(plan.getActualQuantity());
            
            result.add(detail);
        });
        
        return result;
    }
}
